import * as React from 'react';
import './picker.scss';


/** global: BMap */
function getBMap(cb) {
    if (window.BMap) {
        return cb(null, window.BMap);
    }

    let script = document.createElement('script');
    script.src = 'http://api.map.baidu.com/api?v=2.0&ak=H1keGu5vIWDTEvPhybxeh7qsrnwRB2Tx&callback=_bmap_callback';

    window._bmap_callback = () => {
        cb(null, window.BMap);
    };

    document.body.appendChild(script);
}

function formatValue(value, point) {
    let address  = value.address || [value.province,  value.city === value.province ? null : value.city,  value.district, value.street, value.business].filter(item => item).join('');

    return {
        address: address,
        province: value.province,
        city: value.city,
        district: value.district,
        business: value.business,
        lng: point ? point.lng : 0,
        lat: point ? point.lat : 0,
    }
}

function setPlace(map, address, cb) {
    map.clearOverlays();    //清除地图上所有覆盖物
    var local = new BMap.LocalSearch(map, { //智能搜索
      onSearchComplete: () => {
        let pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
        map.centerAndZoom(pp, 18);
        map.addOverlay(new BMap.Marker(pp));    //添加标注

        cb(local.getResults());
      }
    });
    local.search(address);
}

// http://api.map.baidu.com/api?v=2.0&ak=您的密钥&callback=initialize
// amis ak H1keGu5vIWDTEvPhybxeh7qsrnwRB2Tx
export default class MapPicker extends React.PureComponent {

    static defaultProps = {
        geoLocation: false
    };

    constructor(props) {
        super(props);
        this.inputRef = this.inputRef.bind(this);
        this.mapRef = this.mapRef.bind(this);
        this.handleConfirm = this.handleConfirm.bind(this);

        this.inputId = `map_input_${Math.round(Math.random() * 100000)}`;
        this.value = this.props.value;
    }

    componentDidMount() {
        const value = this.props.value || {};
        const self = this;

        getBMap((erro, Bmap) => {
            const map = this.map = new BMap.Map(this.mapDom);
            const geo = this.geo = new Bmap.Geocoder();

            if (value.lng && value.lat) {
                map.centerAndZoom(new BMap.Point(value.lng, value.lat), 11);
                map.addOverlay(new BMap.Marker({
                    lng: value.lng,
                    lat: value.lat
                }));
            } else if (value.address) {
                geo.getPoint(value.address, (point, address) => {
                    var mk = new BMap.Marker(point);
                    map.centerAndZoom(new BMap.Point(point.lng, point.lat), 11);
                    map.addOverlay(mk);
                    map.panTo(point);
                    self.value = formatValue(address, point);
                });
            } else {
                let point = new BMap.Point(116.331398,39.897445);
                map.centerAndZoom(point, 11);

                if (this.props.geoLocation) {
                    let geolocation = new BMap.Geolocation();
                    geolocation.getCurrentPosition(function(r) {
                        if(this.getStatus() == BMAP_STATUS_SUCCESS) {
                            var mk = new BMap.Marker(r.point);
                            map.addOverlay(mk);
                            map.panTo(r.point);
                            self.value = formatValue(r.address, r.point);
                            ac.setInputValue(defself.value.address);
                        }
                    },{enableHighAccuracy: true})
                }
            }

            const navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL});
            map.addControl(navigation);


            const ac = this.ac = new BMap.Autocomplete({
                "input" : this.inputId,
                "location" : map
            });
            ac.setInputValue(value.address || '');

            ac.addEventListener("onconfirm", function(e) {
                let value = formatValue(e.item.value);

                self.value = value;
                setPlace(map, value.address, result => {
                    const poi = result.getPoi(0);
                    self.value = {
                        ...self.value,
                        ...poi.point
                    };
                });
            });

            map.addEventListener("click", e => {
                geo.getLocation(e.point, function({address, addressComponents, business, point}){
                    self.value = formatValue({
                        address,
                        addressComponents,
                        business
                    }, point);
                    map.clearOverlays();
                    var mk = new BMap.Marker(point);
                    map.addOverlay(mk);
                    map.panTo(point);
                    ac.setInputValue(self.value.address);
                });
            });
        });
    }

    shouldComponentUpdate() {
        return false;
    }

    componentWillUnmount() {
        this.ac && this.ac.dispose();
    }

    mapRef(dom) {
        this.mapDom = dom;
    }

    inputRef(dom) {
        this.inputDom = dom;
    }

    handleConfirm() {
        if (this.value) {
            this.props.onChange(this.value);
            this.props.onRequestClose();
        }
    }



    render() {
        let {
            value
        } = this.props;

        value = value || {};

        return (
            <div className="map__picker panel panel-default m-b-none no-border no-shadow">
                <div className="wrapper-sm">
                    <input id={this.inputId} ref={this.inputRef} className="form-control" />
                </div>
                <div className="map__container text-center" ref={this.mapRef}><i className="fa fa-spinner fa-spin fa-2x fa-fw" /></div>
                <div className="panel-footer">
                    <a className="btn btn-default" onClick={this.props.onRequestClose}>关闭</a>
                    <a className="btn btn-info" onClick={this.handleConfirm} >确定</a>
                </div>
            </div>
        );
    }
}
